import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { View, StyleSheet, Alert, TouchableOpacity, ScrollView, Vibration } from 'react-native';
import { Icon, List, ListItem, Button, SearchBar } from 'react-native-elements';
import { primaryColor, executor, toast } from './utils';
import { StoragePageQuery } from './graphql';
import StoreList from './components/StoreList';

const styles = StyleSheet.create({
  button: {
    marginTop: 16
  }
});

class StoreMovePage extends Component {
  static navigationOptions = ({navigation, screenProps}) => {
    return {
      title: `Move ${navigation.state.params.itemIds.length} Items`,
    };
  }
  onSelectStore = (store) => {
    const itemIds = this.props.navigation.state.params.itemIds;

    Alert.alert(
      `Move ${itemIds.length} item${itemIds.length>1?'s':''} to ${store.title}?`,
      null,
      [
        {text: 'Cancel'},
        {text: 'Move', onPress: () => {
          executor(this.props.storeCheckOut, store.id)
            .then(({res}) => {
              if (res) {
                toast('Moved');
                this.props.navigation.goBack();
                this.props.navigation.state.params.onSuccess();
              }
            });
          toast('Moving...');
        }},
      ],
      { cancelable: true }
    );
  }
  render() {
    return (
      <StoreList onSelect={this.onSelectStore}/>
    );
  }
}

export default graphql(gql`
  mutation storeCheckOut($itemIds:[String]!,$moveToStoreId:String) {
    storeCheckOut(itemIds:$itemIds,moveToStoreId:$moveToStoreId)
  }
`, {
  name: 'storeCheckOut',
  props: ({ownProps:{navigation:{state:{params:{itemIds, storeId, search}}}}, storeCheckOut}) => {
    return {
      storeCheckOut: (moveToStoreId) => storeCheckOut({
        variables:{itemIds, moveToStoreId},
        refetchQueries: [{
          query: StoragePageQuery,
          variables: {
            storeId,
            search
          },
        }],
      })
    };
  }
})(StoreMovePage);

